package com.zzjson.concurrency.loopthread;

import lombok.SneakyThrows;

/**
 * @Author 霄池
 * @Date 2023/7/31 23:54
 */
public class WaitNotifyThread {
    private static final Object lockObject = new Object();

    public static int loopNum = 0;

    public static void main(String[] args) {

        Thread threadA = new Thread(() -> {
            print(0);
        }, "A");

        Thread threadB = new Thread(() -> {
            print(1);
        }, "B");

        Thread threadC = new Thread(() -> {
            print(2);
        }, "C");

        threadA.start();

        threadB.start();

        threadC.start();

    }

    @SneakyThrows
    private static void print(int flag) {

        synchronized (lockObject) {
            while (loopNum % 3 != flag) {
                //需要注意
                // 1. wait 会释放对象锁，所以 其他线程可以进入。
                // 2. wait 需要在锁的内部进行
                lockObject.wait();
            }

            System.out.println(Thread.currentThread().getName());

            ++loopNum;
            lockObject.notify();
        }
    }
}
